package com.putao.album.tag;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.RequestParams;
import com.putao.album.R;
import com.putao.album.base.BaseActivity;
import com.putao.album.dialog.DialogBuilder;
import com.putao.album.dialog.DialogBuilderFactory;
import com.putao.album.dialog.ImportDialogBuilder;
import com.putao.album.eventbus.BasePostEvent;
import com.putao.album.util.ActivityHelper;
import com.putao.album.util.CommonUtils;
import com.putao.album.util.HttpRequestUtil;
import com.putao.album.util.Loger;
import com.putao.album.util.PuTaoConstants;
import com.putao.album.util.StringHelper;
import com.putao.album.widget.pttag.PtTag;
import com.putao.album.widget.pttag.PtTagListView;
import com.putao.album.widget.pttag.PtTagView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by jidongdong on 15/4/28.
 * <p/>
 * 标签管理页
 */
public class ActivityTagManager extends BaseActivity {
    private TextView title_tv;
    //    private EditText etx_tag;
    private LinearLayout tag_list_view;
    private RelativeLayout list_empty_view;
    private Button right_btn;
    private PtTagListView mTagListView;
    private final List<PtTag> mTags = new ArrayList<PtTag>();
    private boolean mFlagUpdateTag = false;


    @Override
    public int doGetContentViewId() {
        return R.layout.activity_tag_manager;
    }

    @Override
    public void doInitSubViews(View view) {
        setPageTitle();
        queryViewById(R.id.back_btn, true);
        right_btn = queryViewById(R.id.right_btn, true);
        tag_list_view = queryViewById(R.id.tag_list_view);
        list_empty_view = queryViewById(R.id.list_empty_view);
//        etx_tag = queryViewById(R.id.etx_tag);
        right_btn.setBackgroundResource(R.drawable.tag_button_addtag);
        mTagListView = queryViewById(R.id.tagview);
        mTagListView.setTagViewBackgroundRes(R.drawable.tag_bg_tag);
//        etx_tag.setOnEditorActionListener(mOnTagEditorListener);
    }

//    EditText.OnEditorActionListener mOnTagEditorListener = new EditText.OnEditorActionListener() {
//
//        @Override
//        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//            if (actionId == EditorInfo.IME_ACTION_DONE) {
//                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//                doAddTag();
//                return true;
//            }
//            return false;
//        }
//    };


    /**
     * 获取用户标签
     */
    void doGetUserTag() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", CommonUtils.getUsrId());
        HttpRequestUtil.doHttpGetRequest(mContext, PuTaoConstants.API_GET_USER_TAG, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), true, new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        JSONArray data = HttpRequestUtil.getResponseDataArray(response);
                        if (data != null) {
                            for (int i = 0; i < data.length(); i++) {
                                try {
                                    JSONObject o = data.getJSONObject(i);
                                    mTags.add(new PtTag(o.optInt("id"), o.optString("name")));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            refreshTagList();
                        }
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                    showEmptyView();
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
                showEmptyView();
            }
        });

    }

    /**
     * 添加用户标签
     *
     * @param tagText
     */
    void doAddTag(final String tagText) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", CommonUtils.getUsrId());
        params.put("tag", tagText);
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_ADD_USER_TAG, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {
                        int tag_id = Integer.valueOf(HttpRequestUtil.getResponseData(response).optString("tagId"));
                        addTagItem(tag_id, tagText);
                        refreshTagList();
                        Bundle bundle = new Bundle();
                        bundle.putString("tag_name", tagText);
                        bundle.putString("tag_id", tag_id + "");
                        ActivityHelper.startActivity(mActivity, ActivityTagAlbumPhotoAdd.class, bundle);
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }

    /**
     * 删除用户标签
     *
     * @param tag
     */
    void doDelTag(final PtTag tag) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uid", CommonUtils.getUsrId());
        params.put("tag_id", tag.getId() + "");
        HttpRequestUtil.doHttpPostRequest(mContext, PuTaoConstants.API_DEL_USER_TAG, new RequestParams(HttpRequestUtil.buildHttpRequestParams(params)), new HttpRequestUtil.RequestResponseListener() {
            @Override
            public void success(int statuscode, String response) {
                if (!StringHelper.isEmpty(response)) {
                    if (HttpRequestUtil.getResponseCode(response).equals(HttpRequestUtil.ResponseCode.api_code_200)) {

                        removeTagItem(tag);
                    } else {
                        showToast(HttpRequestUtil.getResponseErrorMsg(response));
                    }
                }
            }

            @Override
            public void failed(int statuscode, String response) {
                Loger.d("response:::" + response);
                showToast(response);
            }
        });
    }


    /**
     * 添加一个标签
     *
     * @param tag_Id
     * @param tagtext
     */
    void addTagItem(int tag_Id, String tagtext) {
        mTags.add(new PtTag(tag_Id, tagtext));
        refreshTagList();
    }

    /**
     * 移除一个标签
     *
     * @param tag
     */
    void removeTagItem(PtTag tag) {
        mTags.remove(tag);
        refreshTagList();
    }

    /**
     * 刷新标签列表View
     */
    void refreshTagList() {
        mTagListView.setTags(mTags, true);
        showEmptyView();
    }


    void setPageTitle() {
        title_tv = queryViewById(R.id.title_tv);
        title_tv.setText(R.string.page_title_tag_manager);
    }

    @Override
    public void doInitData() {
        //设置标签模式是否为删除模式，默认非删除模式
        mTagListView.setDeleteMode(true);
        mTagListView.setTags(mTags);
        mTagListView.setOnTagClickListener(new PtTagListView.OnTagClickListener() {
            @Override
            public void onTagClick(PtTagView tagView, PtTag tag) {
                showDelTipDialog(tag);
            }
        });
        doGetUserTag();

    }

    void showEmptyView() {
        if (mTags.size() == 0) {
            list_empty_view.setVisibility(View.VISIBLE);
            tag_list_view.setVisibility(View.GONE);
        } else {
            list_empty_view.setVisibility(View.GONE);
            tag_list_view.setVisibility(View.VISIBLE);
        }
    }

    void showImportDialog() {
        new DialogBuilderFactory<ImportDialogBuilder>(mContext, DialogBuilderFactory.DialogType.IMPORT)
                .Builder()
                .setDialogButtonOnClickListener(mAddTagDialogListener)
                .setMessage("添加新标签")
                .setNegativeButton(R.string.btn_ok)
                .setPositiveButton(R.string.btn_cancle).Create().show();
    }

    ImportDialogBuilder.DialogButtonOnClickListener mAddTagDialogListener = new ImportDialogBuilder.DialogButtonOnClickListener() {
        @Override
        public void positiveOnClick(Dialog dialog, String importText) {
            dialog.dismiss();
        }

        @Override
        public void negativeOnClick(Dialog dialog, String importText) {
            dialog.dismiss();
            if (!StringHelper.isEmpty(importText)) {
                doAddTag(importText);
                mFlagUpdateTag = true;
            }
        }
    };

    void showDelTipDialog(final PtTag tag) {
        DialogBuilder builder = new DialogBuilderFactory(mContext).Builder();
        Dialog dialog = builder.setMessage("如果删除该标签，则该标签会从所有打过的照片上移除")
                .setNegativeButton(R.string.btn_delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mFlagUpdateTag = true;
                        doDelTag(tag);
                        dialog.dismiss();
                    }
                })
                .setPositiveButton(R.string.btn_cancle, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).Create();
        dialog.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                if (mFlagUpdateTag) {
                    EventBus.getDefault().post(new BasePostEvent(PuTaoConstants.EVENTBUS_DELETE_OR_ADD_TAG_SUCCESS));
                }
                finish();
                break;
            case R.id.right_btn:
                showImportDialog();
                break;
        }
    }
}
